<template>
  <div :id="state.id" class="tiny-textarea"></div>
  <p v-if="state.err">{{ state.err }}</p>
</template>

<script  lang="ts" >
export default {
  name: "Vue3Tinymce",
};
</script>

<script lang="ts" setup>
// http://jsdawn.gitee.io/vue3-tinymce/#%E8%8E%B7%E5%8F%96%E7%BB%84%E4%BB%B6
// http://tinymce.ax-z.cn/

import {
  reactive,
  watch,
  onMounted,
  onBeforeUnmount,
  onActivated,
  onDeactivated,
} from "vue";

import {
  uuid,
  getTinymce,
  getContent,
  setContent,
  resetContent,
  setModeDisabled,
  imageUploadHandler,
} from "./utils";

import { scriptLoader } from "./scriptLoader";
//引入主文件
import "tinymce/tinymce.min.js";
import "tinymce/themes/silver/theme.min.js";
import "tinymce/icons/default/icons.min.js";
//插件js
import "tinymce/themes/silver"; //编辑器主题，不引入则报错
import "tinymce/icons/default"; //引入编辑器图标icon，不引入则不显示对应图标
//中文语言包加入
import "./langs/zh_CN";

// 引入编辑器插件
import "tinymce/plugins/advlist"; //高级列表 有序 / 无序列表
import "tinymce/plugins/anchor"; //锚点
import "tinymce/plugins/autolink"; //自动链接
import "tinymce/plugins/autoresize"; //编辑器高度自适应,注：plugins里引入此插件时，Init里设置的height将失效
import "tinymce/plugins/autosave"; //自动存稿
import "tinymce/plugins/charmap"; //特殊字符
import "tinymce/plugins/code"; //编辑源码
import "tinymce/plugins/codesample"; //代码示例
import "tinymce/plugins/directionality"; //文字方向
import "tinymce/plugins/emoticons"; //表情
import "tinymce/plugins/fullpage"; //文档属性
import "tinymce/plugins/fullscreen"; //全屏
import "tinymce/plugins/help"; //帮助
import "tinymce/plugins/hr"; //水平分割线
import "tinymce/plugins/image"; //插入编辑图片
import "tinymce/plugins/importcss"; //引入css
import "tinymce/plugins/insertdatetime"; //插入日期时间
import "tinymce/plugins/link"; //超链接
import "tinymce/plugins/lists"; //列表插件
import "tinymce/plugins/media"; //插入编辑媒体
import "tinymce/plugins/nonbreaking"; //插入不间断空格
import "tinymce/plugins/pagebreak"; //插入分页符
import "tinymce/plugins/paste"; //粘贴插件
import "tinymce/plugins/preview"; //预览
import "tinymce/plugins/print"; //打印
import "tinymce/plugins/quickbars"; //快速工具栏
import "tinymce/plugins/save"; //保存
import "tinymce/plugins/searchreplace"; //查找替换
import "tinymce/plugins/spellchecker"; //拼写检查，暂未加入汉化，不建议使用
import "tinymce/plugins/tabfocus"; //切入切出，按tab键切出编辑器，切入页面其他输入框中
import "tinymce/plugins/table"; //表格
import "tinymce/plugins/template"; //内容模板
import "tinymce/plugins/textcolor"; //文字颜色
import "tinymce/plugins/textpattern"; //快速排版
import "tinymce/plugins/toc"; //目录生成器
import "tinymce/plugins/visualblocks"; //显示元素范围
import "tinymce/plugins/visualchars"; //显示不可见字符
import "tinymce/plugins/wordcount"; //字数统计
import "tinymce/plugins/imagetools"; //图片编辑工具


const props = defineProps({
  modelValue: String,
  setting: { type: Object, default: () => ({}) },
  setup: Function,
  disabled: Boolean,
  scriptSrc: String,
  debug: Boolean,
});

const emit = defineEmits(["update:modelValue", "init", "change"]);

let mounting = true;

const state = reactive({
  editor: null,
  id: uuid("tinymce"),
  err: "",
});

const getModelValue = () => String(props.modelValue ?? "");

const updateValue = (val) => emit("update:modelValue", val);

const printLog = (e, val, oldVal) => {
  if (!props.debug) return;
  console.log(`来自：${e.type} | \n ${val} \n ${oldVal || "--"}`);
};

const onChanged = (e, editor) => {
  if (!editor) editor = state.editor;

  const content = getContent(editor);
  printLog(e, content);

  updateValue(content);
  emit("change", content);
};

const onInited = (editor) => {
  state.editor = editor;

  setContent(getModelValue(), editor);

  if (props.disabled && editor.mode.get() !== "readonly") {
    setModeDisabled(editor);
  }

  // change input undo redo keyup
  editor.on("change input undo redo", (e) => {
    onChanged(e, editor);
  });

  emit("init", editor);
};

const initEditor = () => {
  
  if (getTinymce() === null) {
    state.err = "tinymce is null";
    return;
  }

  if (props.debug) {
    console.warn("vue3-tinymce 进入debug模式");
  }
  let setting = {
    ...props.setting,
    // relative_urls: true,
    remove_script_host: true,
     base_url: '..',
    
    selector: "#" + state.id,
    setup: (editor) => {
      if (props.setup) props.setup(editor);
      editor.on("init", () => onInited(editor));
    },
  };

  // custom_images_upload true
  if (props.setting.custom_images_upload) {
    setting.images_upload_handler = (...arg) => {
      imageUploadHandler.apply(null, [props.setting || {}, ...arg]);
    };
  }
  getTinymce().init(setting);

  mounting = false;
};

watch(
  () => props.modelValue,
  (val, oldVal) => {
    if (!state.editor || !state.editor.initialized) return;
    if (oldVal === val || val === getContent(state.editor)) return;

    printLog({ type: "propsChanged to setContent" }, val, oldVal);

    if (val === null) return resetContent("", state.editor);
    setContent(getModelValue(), state.editor);
  }
);

watch(
  () => props.disabled,
  (val) => {
    if (!state.editor || !state.editor.initialized) return;
    setModeDisabled(state.editor, val);
  }
);

defineExpose({
  id: state.id,
  editor: state.editor,
});

onMounted(() => {
  if (getTinymce() !== null) {
    initEditor();
    return;
  }
  const scriptSrc =
    props.scriptSrc ?? "https://cdn.bootcdn.net/ajax/libs/tinymce/5.8.2/tinymce.min.js";
  scriptLoader.load(scriptSrc, initEditor);
});

onActivated(() => {
  if (!mounting) initEditor();
});

onDeactivated(() => {
  if (!state.editor) return;
  state.editor.remove();
});

onBeforeUnmount(() => {
  if (!state.editor) return;
  state.editor.remove();
});
</script>

<style></style>
